package com.jagochan.module.business.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.jagochan.module.business.mapper.UserMapper;
import com.jagochan.module.business.pojo.po.User;
import com.jagochan.module.business.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    /**
     * 存储手机号和验证码的映射关系
     */
    private static final Cache<String, String> PHONE_CODE_CACHE = Caffeine.newBuilder()
            .maximumSize(900)
            .expireAfterWrite(Duration.ofMinutes(10))
            .build();

    /**
     * 根据用ID集合查询用户
     *
     * @param userIdSet 用户ID集合
     * @return 用户ID作为KEY，用户对象作为VALUE的MAP
     */
    @Override
    public Map<Long, User> mapByIds(Set<Integer> userIdSet) {
        if (userIdSet.isEmpty()) return new HashMap<>();
        List<User> userList = listByIds(userIdSet);
        if (userList == null) return new HashMap<>();
        return userList.stream().collect(Collectors.toMap(User::getId, item -> item));
    }

    @Override
    public String sendCode(String phone) {
        String code = RandomUtil.randomNumbers(5);
        PHONE_CODE_CACHE.put(phone, code);
        return code;
    }

    /**
     * 校验验证码
     *
     * @param phone 手机号
     * @param code  验证码
     * @return 验证码校验成功则返回success，否则返回错误信息
     */
    private String checkCode(String phone, String code) {
        String cacheCode = PHONE_CODE_CACHE.getIfPresent(phone);
        if (cacheCode == null) return "验证码已过期";
        if (!cacheCode.equals(code)) return "验证码错误";
        return "success";
    }

}